package com.sk.leetcode.arithmetic.test1_10;

/**
 * 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储，它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
 * 你可以假设除了数字 0 之外，这两个数字都不会以零开头。
 */
public class Test2 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(0);
        l1.next = new ListNode(4);
        //l1.next.next = new ListNode(8);

        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);

        ListNode listNode = addTwoNumbers(l1, l2);
        System.out.println(listNode);

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null) {
            return l2;
        }
        if(l2 == null) {
            return l1;
        }

        ListNode result = null;
        int c = 0;
        if((l1.val + l2.val) > 9) {
            result = new ListNode((l1.val + l2.val) - 10);
            c = 1;
        } else {
            result = new ListNode(l1.val + l2.val);
        }
        ListNode lin = result;

        while (l1.next != null || l2.next != null) {

            int a = 0, b = 0;
            if(l1.next != null) {
                l1 = l1.next;
                a = l1.val;
            }
            if(l2.next != null) {
                l2 = l2.next;
                b = l2.val;
            }
            int d = a + b + c;
            if(d > 9) {
                lin.next = new ListNode(d - 10);
                c = 1;
            } else {
                lin.next = new ListNode(d);
                c = 0;
            }

            lin = lin.next;
        }
        if(c==1){
            lin.next = new ListNode(1);
        }

        return result;
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}
